package com.lagou.cl.dao.impl;

import com.lagou.cl.annotation.MyAutowired;
import com.lagou.cl.annotation.MyRepository;
import com.lagou.cl.dao.AccountDao;
import com.lagou.cl.pojo.Account;
import com.lagou.cl.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 程  林
 * @date 2020-04-01 10:22
 * @description //
 * @since V1.0.0
 */
@MyRepository(value = "jdbcAccountDaoImpl")
public class JdbcAccountDaoImpl implements AccountDao {

	@MyAutowired
	private ConnectionUtils connectionUtils;

	@Override
	public Account queryAccountByCardNo(String cardNo) throws Exception {

		//从当前线程当中获取绑定的connection连接
		Connection con = connectionUtils.getCurrentThreadConn();

		String sql = "select * from account where cardNo=?";
		PreparedStatement preparedStatement = con.prepareStatement(sql);
		preparedStatement.setString(1, cardNo);
		ResultSet resultSet = preparedStatement.executeQuery();

		Account account = new Account();
		while (resultSet.next()) {
			account.setCardNo(resultSet.getString("cardNo"));
			account.setName(resultSet.getString("name"));
			account.setMoney(resultSet.getInt("money"));
		}

		resultSet.close();
		preparedStatement.close();

		//不能关闭连接，关闭以后，有需要重新拿去连接
		//con.close();

		return account;
	}

	@Override
	public int updateAccountByCardNo(Account account) throws Exception {


		//从当前线程当中获取绑定的connection连接
		Connection con = connectionUtils.getCurrentThreadConn();

		String sql = "update account set money=? where cardNo=?";
		PreparedStatement preparedStatement = con.prepareStatement(sql);
		preparedStatement.setInt(1, account.getMoney());
		preparedStatement.setString(2, account.getCardNo());
		int i = preparedStatement.executeUpdate();

		preparedStatement.close();
		//con.close();

		return i;
	}
}
